# -*- coding: utf-8 -*-
# created by Src - 一路好时光

# 2.10 练习题-全局⽂本检索替换
# 写⼀个脚本，允许⽤户按以下⽅式执⾏时，即可以对指定⽂件内容进⾏全局替换，且替换完毕后打印替
# 换了多少处内容
# 写完后的脚本调⽤⽅式：
# python your_script.py old_str new_str filename

# (.venv) PS E:\PycharmProjects\pythonProject\day4-用Python处理文件> python 10-file_replace.py arg1 agr2 3
# ['10-file_replace.py', 'arg1', 'agr2', '3']

import sys

print(sys.argv)

old_str = sys.argv[1]
new_str = sys.argv[2]
filename=sys.argv[3]

#1.load into ram
f=open(filename,"r+")
data=f.read()

#2.count and replace
old_str_count = data.count(old_str)
new_data = data.replace(old_str,new_str)

#3.clear old filename
f.seek(0)
f.truncate()

#4.save new data into file
f.write(new_data)

print(f"成功替换字符'{old_str}' to '{new_str}',共{old_str_count}处...")


# src1
# src2
# src3
# srcsrc4
# ...

#(.venv) PS E:\PycharmProjects\pythonProject\day4-用Python处理文件> python 10-file_replace.py src shi file_replace.txt
# ['10-file_replace.py', 'src', 'shi', 'file_replace.txt']
# 成功替换字符'src' to 'shi',共5处...

#替换完成后文件
# shi1
# shi2
# shi3
# shishi4
# ...

